package com.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class NioServer1 {
    private static Map<String, SocketChannel> clientMap = new HashMap<>();

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8899));
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            for (SelectionKey selectionKey : selectionKeys) {
                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                    System.out.println("---- NioServer  Acceptable ; 接受客户端请求链接 ");
                    ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    //注册事件
                    sc.register(selector, SelectionKey.OP_READ);
                    // 存储客户端
                    String key = "【" + sc.getRemoteAddress() + "】";
                    clientMap.put(key, sc);
                } else if (selectionKey.isValid() && selectionKey.isReadable()) {
                    byteBuffer.clear();
                    SocketChannel sc = (SocketChannel) selectionKey.channel();
                    try {
                        int count = sc.read(byteBuffer);
                        byteBuffer.flip();
                        if (count > 0) {
                            String msg = String.valueOf(StandardCharsets.UTF_8.decode(byteBuffer).array());
                            System.out.println("---- NioServer  Readable ; 客户端【" + sc.getRemoteAddress() + "】发送的信息 ：" + msg);
                            // 消息分发
                            for (Entry<String, SocketChannel> entry : clientMap.entrySet()) {
                                byteBuffer.clear();
                                if (entry.getValue().equals(sc)) {
                                    byteBuffer.put(("自己发送的消息  :  " + msg).getBytes());
                                } else {
                                    byteBuffer.put((entry.getKey() + "客户端发送的消息  :  " + msg).getBytes());
                                }
                                byteBuffer.flip();
                                entry.getValue().write(byteBuffer);
                            }
                        }
                    } catch (Exception e) {
                        selectionKey.cancel();
                    }
//					sc.register(selector, SelectionKey.OP_WRITE);
                }
//				else if(selectionKey.isValid()&&selectionKey.isWritable()){
//					SocketChannel sc =(SocketChannel)selectionKey.channel();
//					byteBuffer.clear();
//					System.out.println("---- NioServer  Writable -----");
//					sc.register(selector, SelectionKey.OP_READ);
//				}
                selectionKeys.remove(selectionKey);
            }
        }
    }
}
